/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pv168.uloha3.swing.workers;

import cz.muni.fi.pv168.uloha3.common.DBUtils;
import cz.muni.fi.pv168.uloha3.entities.Owner;
import cz.muni.fi.pv168.uloha3.entities.Ownership;
import cz.muni.fi.pv168.uloha3.entities.RealEstate;
import cz.muni.fi.pv168.uloha3.exceptions.RealEstateManagerException;
import cz.muni.fi.pv168.uloha3.managers.OwnerManager;
import cz.muni.fi.pv168.uloha3.managers.OwnershipManager;
import cz.muni.fi.pv168.uloha3.managers.RealEstateManager;
import cz.muni.fi.pv168.uloha3.managers.impl.OwnerManagerImpl;
import cz.muni.fi.pv168.uloha3.managers.impl.OwnershipManagerImpl;
import cz.muni.fi.pv168.uloha3.managers.impl.RealEstateManagerImpl;
import cz.muni.fi.pv168.uloha3.swing.EstatesTableModel;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;
import javax.swing.SwingWorker;

/**
 *
 * @author stefan
 */
public class EstateListAllSwingWorker extends SwingWorker<Set<RealEstate>, Object> {

    private final EstatesTableModel model;
    private final Owner excludeForOwner;
    
    public EstateListAllSwingWorker(EstatesTableModel model) {
        this.excludeForOwner = null;
        this.model = model;
    }
    
    public EstateListAllSwingWorker(Owner excludeForOwner, EstatesTableModel model) {
        this.excludeForOwner = excludeForOwner;
        this.model = model;
    }
    
    @Override
    protected Set<RealEstate> doInBackground() throws Exception {
        Set<RealEstate> retval = new HashSet<RealEstate>();
        
        DataSource dataSource = DBUtils.initConnector();
        
        RealEstateManager managerRealEstate = new RealEstateManagerImpl();
        managerRealEstate.setDataSource(dataSource);
        
        model.clearAllEstates();

        try {
            retval.addAll(managerRealEstate.listRealEstates());
            
            if(excludeForOwner != null) {
                OwnerManager managerOwner = new OwnerManagerImpl();
                managerOwner.setDataSource(dataSource);
                OwnershipManager managerOwnership = new OwnershipManagerImpl();
                managerOwnership.setDataSource(dataSource);
                managerOwnership.setOwnerManager(managerOwner);
                managerOwnership.setRealEstateManager(managerRealEstate);
                for(Ownership ownership : managerOwnership.getOwnershipsByOwner(excludeForOwner)) {
                    retval.remove(ownership.getRealEstate());
                }
            }
        } catch (RealEstateManagerException ex) {
            Logger.getLogger(EstateListAllSwingWorker.class.getName()).log(Level.SEVERE, null, ex);
            return retval;
        }
        
        model.addAllEstates(retval);
        return retval;
    }
}